package controller

import (
	"github.com/gin-gonic/gin"
	"io/ioutil"
	"net/http"
	"strings"
)

func PostmanPage(c *gin.Context) {
	c.HTML(http.StatusOK, "postman.html", gin.H{})
}

func PostmanSendData(c *gin.Context) {
	urlRequest := c.PostForm("url")
	header := c.PostForm("header")
	data := c.PostForm("data")
	requestType := c.PostForm("type")

	req, err := http.NewRequest(requestType, urlRequest, strings.NewReader(data))
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": -1,
			"resp": err,
		})
		return
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	req.Header.Set("Connection", "Keep-Alive")
	headers := strings.Split(header, "&")
	for _, v := range headers {
		s := strings.Split(v, "=")
		if len(s) != 2 {
			break
		}
		key := s[0]
		value := s[1]
		req.Header.Set(key, value)
	}
	resp, err := (&http.Client{}).Do(req)

	bytes, err := ioutil.ReadAll(resp.Body)
	c.JSON(http.StatusOK, gin.H{
		"code": 1,
		"resp": string(bytes),
	})
}
